# _*_ coding:utf-8 _*_
# @Time  : 2023.08.31
# @Author: zizlee

from fastapi import APIRouter, Query, Body
from response import APIResponse
from db_utils import BaseDatabaseConnection
from utils.validate_util import DateRangeValidator


class BindAccountItem(DateRangeValidator):
    user_id: int
    cust_num: str


class CustNumber:
    def retrieve_list(self, kw: str):
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute("SELECT fund_num FROM ac_fund WHERE fund_num LIKE %s GROUP BY fund_num;", [f'%{kw}%'])
            cust_list = list(conn.cursor.fetchall())
        return APIResponse.success(data=cust_list)


class ExDoctorAdmin:
    def __init__(self, user_id: int):
        self.user_id = user_id

    def query_bind_info(self):
        sql = """
            SELECT a.id,a.create_time,a.user_id,a.cust_num,a.start_date,a.end_date,a.diagnosis_count,a.is_active,b.username
            FROM ruizhi_user_exchange_doctor As a 
            INNER JOIN ruizhi_user As b ON a.user_id=b.id 
            WHERE a.user_id=%s;
        """
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute(sql, [self.user_id])
            ret_list = list(conn.cursor.fetchall())
        active_list = list(filter(lambda x: x['is_active'], ret_list))
        history_list = list(filter(lambda x: not x['is_active'], ret_list))
        return APIResponse.success(data={'active_list': active_list, 'history_list': history_list})

    def create_bind_info(self, bind: BindAccountItem):
        with BaseDatabaseConnection() as conn:
            # 存在的有效记录失效
            inactive_count = conn.cursor.execute("UPDATE ruizhi_user_exchange_doctor SET is_active=0 WHERE user_id=%s AND is_active=1;", [self.user_id])
            # 添加新的绑定
            active_count = conn.cursor.execute("INSERT INTO ruizhi_user_exchange_doctor(user_id,cust_num,start_date,end_date) VALUES (%s,%s,%s,%s);",
                                               [bind.user_id, bind.cust_num, bind.start_date, bind.end_date])

        return APIResponse.success(msg=f'添加新的绑定成功,原绑定失效{inactive_count}个，新增绑定{active_count}个!')


ex_doctor_api = APIRouter()


@ex_doctor_api.get('/custList/')  # 资金账号列表
def retrieve_cust_list(kw: str = Query(...)):
    return CustNumber().retrieve_list(kw=kw)


@ex_doctor_api.get('/bindAccount/')  # 查询账户绑定情况
def retrieve_bind_account(uid: int = Query(...)):
    return ExDoctorAdmin(user_id=uid).query_bind_info()


@ex_doctor_api.post('/bindAccount/')  # 绑定诊断资金号
def create_bind_account(bind_item: BindAccountItem = Body(...)):
    return ExDoctorAdmin(user_id=bind_item.user_id).create_bind_info(bind=bind_item)
